Python Tutorial 0

Tzer-jen Wei

What is Python?

Interpreted, Object-Oriented

Why Python?

2nd Best Language for everything

  • Web
  • Scientific computation
  • Statistics
  • Data Science
  • Game
  • Education
  • Computer Vision

Ecosystem

Batteries Included

Python Code


In [58]:
print("Hello World")


Hello World

In [59]:
3**128


Out[59]:
11790184577738583171520872861412518665678211592275841109096961

In [61]:
3**0.5, 3/2


Out[61]:
(1.7320508075688772, 1.5)

In [27]:
def isqrt(n):    
    x, y = n+1, n
    while y < x:
        x, y = y, (y + n // y) // 2
    return x

In [19]:
print(isqrt(99))


9

In [30]:
def isqrt(n):
    def f(a, b):
        return f(b, (b+n//b)//2) if b < a else a
    return f(n+1, n)

In [63]:
%%timeit
for i in range(1, 10**5):
    r = isqrt(i)
    assert r**2<=i and (r+1)**2 >= i


1 loops, best of 3: 450 ms per loop

In [48]:
def is_prime(n):
    r = isqrt(n)
    for i in range(2, r+1):
        if n%i == 0:
            return False
    return True

In [51]:
primes = [n for n in range(2,100) if is_prime(n)]
print(primes)
print(len(primes))


[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
25

In [56]:
def is_prime(n):
    r = isqrt(n)
    return all(n%i !=0 for i in range(2, r+1))

In [57]:
primes2 = [n for n in range(2,100) if is_prime(n)]
print(primes == primes2)


True

In [ ]:
!git clone https://github.com/tjwei/PythonTutorial